//
//  YFSportViewController.m
//  SquashSpark
//
//  Created by Coollang on 2017/10/26.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFSportViewController.h"
#import "UICountingLabel.h"
#import <SquashSpark-Swift.h>
#import "UIView+Frame.h"
#import <zhPopupController/zhPopupController.h>
#import "YFNetError.h"
#import "YFTrackRecordController.h"
#import "MyNavigationViewController.h"
#import "YFTemplateController.h"
#import "YFSportStatisticsVC.h"
#import "YFSensorManager.h"
#import "YFAlertHelper.h"
#import "YFDayPickerAlertView.h"
#import <DateTools/DateTools.h>
#import "NSAttributedString+RichText.h"
#import "YFSportAndSensorApi.h"
#import "YFSportAnalysisVc.h"
#import "YFCreatTemplateVc.h"
#import "YFThreeDViewController.h"
#import "UIScrollView+YFMJRefresh.h"
#import "YFSearchController.h"
#import "DeviceInfo.h"
#import "JCTabBarViewController.h"

//将未上传的数据上传到服务器
NSString * const kuploadBlueDataToServer = @"kuploadBlueDataToServer";

NSString * const kSeguePushAnalysis = @"seguePushAnalysis";

@interface YFSportViewController()

@property (weak, nonatomic) IBOutlet UILabel *daylabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *swingCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *sportDurationLabel;
@property (weak, nonatomic) IBOutlet UILabel *sportCalorieLabel;
@property (weak, nonatomic) IBOutlet UILabel *maxSpeedlabel;
@property (weak, nonatomic) IBOutlet UIButton *goButton;
@property (nonatomic, strong) UIView *visualView;

/** 当前页面展示的是那一天的数据 */
@property (nonatomic, copy) NSString *selectCurrentDay;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *titleButton;

/** 自动连接计时器 */
@property (nonatomic, strong) NSTimer *atuoReconnectTimer;
@property (nonatomic, strong) LGPeripheral *lgPeripheral;
/** 设备重连的次数 */
@property (nonatomic, assign)NSInteger autoReconnectCount;
/** 是否选择了循环自动连接取消弹框提示 */
@property (nonatomic, assign)BOOL notAlertPrompt;

@property (nonatomic, strong) UIAlertController *reconnectAlertController;

@end

@implementation YFSportViewController {
    __block BOOL _downloadHomeDataSuccess;
    /** 是否正在下载主页数据 */
    __block BOOL _isSysHomeData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[User getLastUser] checkAndCreatSystemTemplate];
    _downloadHomeDataSuccess = NO;
    
    [self initializeUI];
    [self updateTitleButton];
    [self regiesterNotification];
    __weak typeof(self) weakSelf = self;
    
    [self.scrollView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
        [weakSelf synchronBlueHomePageDataCompleated:^{
            // 更新数据
            NSArray *haveDays = [weakSelf getHaveDataDays];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.scrollView.mj_header endRefreshing];
                if ([haveDays containsObject:self.selectCurrentDay]) {
                    weakSelf.selectCurrentDay = weakSelf.selectCurrentDay;
                }else {
                    weakSelf.selectCurrentDay = haveDays.lastObject;
                }
            });
        }];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self autoReconnetDevice];
    });
}

// 跳转到运动分析页面
- (IBAction)sportAnalyisBtnClick:(id)sender {
    [self performSegueWithIdentifier:kSeguePushAnalysis sender:nil];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (_downloadHomeDataSuccess == NO) {
        [self downloadHomeData];
    }else {
        [self sysnBlueData];
    }
    if ([YFCommunicationManager shareInstance].isPeripheralConnected) {
        [self.scrollView.mj_header beginRefreshing];
    }
    
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:kSeguePushAnalysis]) {
        YFSportAnalysisVc *analysisVc = (YFSportAnalysisVc *)segue.destinationViewController;
        analysisVc.yearMonthDayStr = self.selectCurrentDay;
    }
}

#pragma mark - 数据同步和上传
- (void)downloadHomeData {
    if (_isSysHomeData) {
        return;
    }
    _isSysHomeData = YES;
    _downloadHomeDataSuccess = NO;
    // SysHomeDataQueue
//    dispatch_async(dispatch_get_global_queue(0, DISPATCH_QUEUE_SERIAL), ^{
        [[YFSensorManager shareSensorManager] sysnHomeDataFromServerCallBlock:^(BOOL sysSuccess) {
            _downloadHomeDataSuccess = sysSuccess;
            _isSysHomeData = NO;
            [self sysnBlueData];
            // 更新数据
            NSArray *haveDays = [self getHaveDataDays];
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([haveDays containsObject:self.selectCurrentDay]) {
                    self.selectCurrentDay = self.selectCurrentDay;
                }else {
                    self.selectCurrentDay = haveDays.lastObject;
                }
            });
        }];
//    });
}

- (void)sysnBlueData {
    // 进入主页或下拉刷新：将设备中未读取的数据读取取出来
    [[YFSensorManager shareSensorManager] updloadHomeDataToServerCompleted:^(NSError *error) {
        // 上传天的详情数据
        [[YFSensorManager shareSensorManager] uploadDetailDataToServerCompleted:^(NSError *error) {
            if (error == nil) {
                NSLog(@"详情数据同步完成");
                self.selectCurrentDay = self.selectCurrentDay;
            }
        }];
    }];
}

// 读取设备数据
- (void)synchronBlueHomePageDataCompleated:(void(^)(void))completed {
    if (![YFCommunicationManager shareInstance].isPeripheralConnected) {
        if (completed) {
            completed();
        }
        return;
    }
//    __weak typeof(self) weakSelf = self;
    [[YFSensorManager shareSensorManager] getBlueHomeDataWithComplete:^(NSArray<YFDayRecordItem *> *sportRecordItems, NSError *error) {
        if (error == nil) {
            // 读取详情数据
            [[YFSensorManager shareSensorManager] syncSwingDayDetailDataWithDayItems:sportRecordItems everydayProgress:^(YFDayRecordItem *dayItem, CGFloat dayProgress) {
                
            } allDayProgress:^(CGFloat totalProgress) {
                // 更新进度
//                [weakSelf.startSearchButton setTitle: [NSString stringWithFormat:@"%0.f",round(totalProgress * 100)] forState:UIControlStateNormal];
//                [weakSelf.progressView setCurrent:@(round(totalProgress * 100))];
//                [weakSelf.progressView strokeChart];
            } compelete:^{
                if (completed) {
                    completed();
                }
            }];
        }else {
            if (completed) {
                completed();
            }
        }
    }];
}

#pragma mark - 通知
- (void)regiesterNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sysnBlueData) name:kuploadBlueDataToServer object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceConnectHandel) name:kLGPeripheralDidConnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceDidDisconnectHandle) name:kLGPeripheralDidDisconnect object:nil];
}

- (void)deviceConnectHandel {
    [self updateTitleButton];
    [self alertControllerViewTapAction];
}
- (void)deviceDidDisconnectHandle {
    [self updateTitleButton];
    YFCommunicationManager *bleManager = [YFCommunicationManager shareInstance];
    
    if (bleManager.isCentralReady && bleManager.isPeripheralConnected == NO) {
        [[YFSensorManager shareSensorManager] circulationReconnect];
        if (self.notAlertPrompt == YES) {
            __weak typeof(self) weakSelf = self;
            UIAlertController *alertController = [YFAlertHelper showAlertController:self Title:nil message: [NSString stringWithFormat:NSLocalizedString(@"Device disconnected, %@ is trying to reconnect", nil),[NSString appCurrentName]] cancelTitle:NSLocalizedString(@"Cancel", nil) defalutTitle:NSLocalizedString(@"No tips", nil) cancelAction:^(UIAlertAction *action) {
                [[YFSensorManager shareSensorManager] removeTimer];
                bleManager.shouldRetryConnect = NO;
                weakSelf.reconnectAlertController = nil;
            } defalutAction:^(UIAlertAction *action) {
                weakSelf.notAlertPrompt = YES;
                weakSelf.reconnectAlertController = nil;
            }];
            self.reconnectAlertController = alertController;
        }
    }
}

- (void)alertControllerViewTapAction {
    if (_reconnectAlertController == nil) {
        return;
    }
    [self.reconnectAlertController dismissViewControllerAnimated:YES completion:^{
        self.reconnectAlertController = nil;
    }];
}
- (void)setReconnectAlertController:(UIAlertController *)reconnectAlertController {
    [self alertControllerViewTapAction];
    _reconnectAlertController = reconnectAlertController;
}
- (void)updateTitleButton {
    if ([YFCommunicationManager shareInstance].isPeripheralConnected) {
        [self.titleButton setTitle:[YFCommunicationManager shareInstance].lgPeripheral.name forState:UIControlStateNormal];
        [self.titleButton setTitleColor:kYellowGreenColor forState:UIControlStateNormal];
    }else {
        [self.titleButton setTitle:@"Unconnected" forState:UIControlStateNormal];
        [self.titleButton setTitleColor:kTLightGray999 forState:UIControlStateNormal];
    }
     self.titleButton.titleLabel.font = kOpenSansFont(OpenSansBoldItalic, 22.0f);
    [self.titleButton sizeToFit];
}

- (IBAction)titleButtonClick:(id)sender {
    [YFSensorManager openSensorControllrWithVc:self isNecessaryOpenSensorVc:NO];
}
#pragma mark - UI更新操作
- (void)initializeUI {

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"total_left_item"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarItemAction:)];
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"connectSensorRightItem"] style:UIBarButtonItemStyleDone target:self action:@selector(connectSensor:)];
    self.selectCurrentDay = [self getHaveDataDays].lastObject;
    self.swingCountLabel.format = @"%d";
    [self.goButton clipsCornerRadius:3];
}

- (void)connectSensor:(UIBarButtonItem *)sender{
    [YFSensorManager openSensorControllrWithVc:self isNecessaryOpenSensorVc:NO];
}

- (void)setSelectCurrentDay:(NSString *)selectCurrentDay {
    _selectCurrentDay = selectCurrentDay;
    // 更新界面
    self.daylabel.text =  [self.selectCurrentDay stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
    //[[NSDate formateYearMonthDayString:self.selectCurrentDay] formattedDateWithFormat:@"yyyy/MM/dd"];
    RLMResults *results = [[YFDayRecordItem getUserAllDayRecordItems] objectsWhere:@"dayDate == %@",self.selectCurrentDay];
    if (results.count > 0) {
        YFDayRecordItem *dayItem = results.firstObject;
        [self.swingCountLabel countFrom:self.swingCountLabel.text.floatValue to:dayItem.dayAmountOfCount withDuration:0.5];
        [self setSportTime:dayItem.sportTimeInterval calorie:dayItem.dayCalories speed:dayItem.maxSwingSpeed];
    }else {
        [self setSportTime:0 calorie:0 speed:0];
    }
}

- (void)setSportTime:(NSInteger)sportTime calorie:(NSInteger)calorie speed:(CGFloat)speed {
    UIFont *bigFont = kOpenSansFont(OpenSansRegular, 27);
    UIFont *smallFont = kOpenSansFont(OpenSansRegular, 12);
  
    self.sportDurationLabel.attributedText = [NSAttributedString attriWithSeconds:sportTime hAndMFont:smallFont numberFont:bigFont textColor:kTWhiteText];
    if (calorie > 0) {
       NSString *calorieStr = [NSString stringWithFormat:@"%zdcal",calorie];
        self.sportCalorieLabel.attributedText = [NSAttributedString attributedString:calorieStr subString:@[@(calorie).stringValue,@"cal"] colors:@[kTWhiteText] fonts:@[bigFont,smallFont]];
    }else {
        self.sportCalorieLabel.text = @"0";
    }
    if (speed > 0) {
        NSString *unitSubStr = NSLocalizedString(@"kph", @"km/h");
        if (![YFUserDefaults generalMetricSystemUnit]) {
            unitSubStr = @"mph";
            speed = [Common kmhToMph:speed];
        }
        NSString *speedSubStr = [NSString stringWithFormat:@"%0.f",speed];
        NSString *speedStr = [NSString  stringWithFormat:@"%0.f%@",round(speed),unitSubStr];
        self.maxSpeedlabel.attributedText = [NSAttributedString attributedString:speedStr subString:@[speedSubStr,unitSubStr] colors:@[kTWhiteText] fonts:@[bigFont,smallFont]];
    }else {
        self.maxSpeedlabel.text = @"0";
    }
}

#pragma mark - action
- (void)leftBarItemAction:(UIBarButtonItem *)item {
    YFSportStatisticsVC *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"YFSportStatisticsVC"];
//    vc.hidesBottomBarWhenPushed = YES;
   [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)selectDayAction:(UIButton *)sender {
    YFDayPickerAlertView *dayPickerView = [YFDayPickerAlertView dayPickerAlertView];
    [dayPickerView configuerWithDays:[self getHaveDataDays] withCurrentDay:self.selectCurrentDay];
    PopupViewController *popVc = [YFAlertHelper showPresentInView:nil alertView:dayPickerView withAlertViewFrame:CGRectMake(0, 0, kAutoWid(300), 280) animationType:DetailViewControllerPresentAnimationTypeUp tapMaskViewDismiss:YES];
    __weak typeof(self) weakSelf = self;
    [dayPickerView setClickConfirmButtonBlock:^(NSDate *selectDay, NSString *selectDayStr) {
        weakSelf.daylabel.text = selectDayStr;
        weakSelf.selectCurrentDay = [selectDay formattedDateWithFormat:@"yyyy-MM-dd"];
        [popVc dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeFade];
    }];
}

- (IBAction)goBtnClick:(UIButton *)sender {
    [self visualViewIsShowUp:YES aniCompleted:nil];
}
- (void)videoData3DButtonAction:(UIButton *)sender {
    [self visualViewIsShowUp:NO aniCompleted:nil];
    if (sender.tag == 100) {// 视频
        YFTrackRecordController *recordVc = [[YFTrackRecordController alloc]  initWithNibName:@"YFTrackRecordController" bundle:nil];
        recordVc.hidesBottomBarWhenPushed = YES;
        AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [appdelegate.window.rootViewController presentViewController:recordVc animated:YES completion:nil];
        
//        [self presentViewController:recordVc animated:YES completion:nil];
    }else if (sender.tag == 101){// 数据
        AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [((JCTabBarViewController *)appdelegate.window.rootViewController) switchControllerIndex:1];
//        YFTemplateController *templateVc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([YFTemplateController class])];
//        templateVc.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:templateVc animated:YES];
    }else {
        // 3d
        AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [((JCTabBarViewController *)appdelegate.window.rootViewController) switchControllerIndex:3];
//        YFCreatTemplateVc *creatVc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"YFCreatTemplateVc"];
//        [self.navigationController pushViewController:creatVc animated:YES];
        
//        YFThreeDViewController *threeDVc = [[YFThreeDViewController alloc] initWithNibName:@"YFThreeDViewController" bundle:nil];
//        [self.navigationController pushViewController:threeDVc animated:YES];
    }
}


- (void)visualViewIsShowUp:(BOOL)up aniCompleted:(void(^)())completed{
    NSArray *buttons = @[[[self creatVisualView] viewWithTag:100],[self.visualView viewWithTag:101],[self.visualView viewWithTag:102]];
    if (up) {
        [[UIApplication sharedApplication].keyWindow addSubview:[self creatVisualView]];
        [self.visualView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo([UIApplication sharedApplication].keyWindow);
        }];
        [UIView animateWithDuration:0.25 animations:^{
            self.visualView.alpha = 1;
        }];
        for (int i = 0; i < buttons.count; i++) {
            UIButton *button = buttons[i];
            CGRect torect = CGRectMake(button.x, kYFScreenHeight - kAutoHei(260), button.width, button.height);
            [[AnimationHelper helper] animationFrameWithView:buttons[i] toValue:torect beginTime:CACurrentMediaTime() + i * 0.06 completed:completed];
        }
    }else {
        for (int i = (int)(buttons.count - 1); i >= 0; i--) {
            UIButton *button = buttons[i];
            CGRect torect = CGRectMake(button.x, kYFScreenHeight, button.width, button.height);
            [UIView animateWithDuration:0.6 animations:^{
                self.visualView.alpha = 0;
            }];
            [[AnimationHelper helper] animationFrameWithView:buttons[i] toValue:torect beginTime:CACurrentMediaTime() + (buttons.count - i - 1) * 0.06 completed:^{
                if (i == 0) {
                    [self.visualView removeFromSuperview];
                }
                if (completed) {
                    completed();
                }
            }];
        }
    }
}

- (UIView *)creatVisualView {
    if (self.visualView == nil) {
       // UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
        //UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:effect];
//        visualView.frame = [UIScreen mainScreen].bounds;
        UIView *visualView = [[UIView alloc] init];
        visualView.backgroundColor = kMaskViewBgColor;
        NSArray *imageNames = @[@"sport_video",@"sport_data",@"sport_3D"];
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(visualViewTap)];
        visualView.userInteractionEnabled = YES;
        [visualView addGestureRecognizer:tapGes];
        for (int i= 0;i < imageNames.count; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setImage:[UIImage imageNamed:imageNames[i]] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(videoData3DButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = 100 + i;
            [button sizeToFit];
            // 计算
            CGFloat margin = (kYFScreenWidth - imageNames.count * button.width) / (imageNames.count + 1);
            button.frame = CGRectMake(margin + (button.width + margin) * i, kYFScreenHeight, button.width, button.height);
            [visualView addSubview:button];
        }
        _visualView = visualView;
    }
    return _visualView;
}

- (void)visualViewTap {
    [self visualViewIsShowUp:NO aniCompleted:nil];
}


#pragma mark - 数据处理
// 获取有数据的天
- (NSArray *)getHaveDataDays {
    // 获取有数据的天数
    RLMResults *results = [YFDayRecordItem getUserAllDayRecordItems];
    NSMutableArray *daysArrM = [NSMutableArray array];
    for (YFDayRecordItem *dayItem in results) {
        [daysArrM addObject:dayItem.dayDate];
    }
    NSString *todayStr = [[NSDate date] year_month_day_dateString];
    if (daysArrM.count == 0) {
        [daysArrM addObject:todayStr];
    }
    NSArray *daysDataArr = [daysArrM sortedArrayUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString *_Nonnull obj2) {
        return [obj1 compare:obj2] != NSOrderedAscending;
    }];
    return daysDataArr;
}

#pragma mark - 设备重连

- (void)autoReconnetDevice {
    DeviceInfo *lastdevice = [DeviceInfo getLastDevice];
    
    [[YFCommunicationManager shareInstance] startScanPeripheralsWithBlock:^(NSArray *peripherals, NSError *error) {
        if (peripherals.count > 0 ) {
            for (LGPeripheral *per in peripherals) {
                if ([per.UUIDString isEqualToString:lastdevice.deviceUUID]) {
                    self.lgPeripheral = per;
                    [self autoConnect:^(BOOL succsee) {
                        if (succsee) {
                            self.lgPeripheral = nil;
                        }
                    }];
                    break;
                }
            }
        }
    }];
    
    self.atuoReconnectTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerStopScan) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:self.atuoReconnectTimer forMode:NSRunLoopCommonModes];
}

- (void)autoConnect:(void(^)(BOOL succsee))callbackColsure {
    if (self.lgPeripheral == nil) {
        if (callbackColsure) {
            callbackColsure(NO);
        }
        return;
    }
    [[YFCommunicationManager shareInstance] stopScanningPeripherals];
    
    [[YFSensorManager shareSensorManager] connectThePeripheral:self.lgPeripheral completed:^(BOOL success, NSError *error) {
        if (success) {
            
        }
        if (callbackColsure) {
            callbackColsure(success);
        }
    }];
}

- (void)timerStopScan {
    // 弹窗提示
    if (self.lgPeripheral == nil && [YFCommunicationManager shareInstance].isPeripheralConnected == NO) {
        [self stopAutoScan];
        
//        UIAlertController *alertController = [YFAlertHelper showAlertController:self Title:NSLocalizedString(@"No device found", nil) message:NSLocalizedString(@"Confirm device is powered on and nearby", nil) cancelTitle:NSLocalizedString(@"Cancel", nil) defalutTitle:NSLocalizedString(@"Search again", nil) cancelAction:^(UIAlertAction *action) {
//
//        } defalutAction:^(UIAlertAction *action) {
//            [self researchPeripherals];
//
//        }];

    }else {
        self.autoReconnectCount += 1;
        if (self.autoReconnectCount >= 3) {
            [self stopAutoScan];
//            UIAlertController *alertController = [YFAlertHelper showAlertController:self Title:NSLocalizedString(@"Automatically connection failed", nil) message:NSLocalizedString(@"Confirm device is powered on and nearby", nil) cancelTitle:NSLocalizedString(@"Cancel", nil) defalutTitle:NSLocalizedString(@"Search again", nil) cancelAction:^(UIAlertAction *action) {
//
//            } defalutAction:^(UIAlertAction *action) {
//                self.autoReconnectCount = 0;
//                [self researchPeripherals];
//            }];
//            self.reconnectAlertController = alertController;
        }else {
            [self researchPeripherals];
        }
    }
}

- (void)stopAutoScan {
    [[YFCommunicationManager shareInstance] stopScanningPeripherals];
    [self.atuoReconnectTimer invalidate];
    self.atuoReconnectTimer = nil;
}
- (void)researchPeripherals {
    self.lgPeripheral = nil;
    [self stopAutoScan];
    [self autoReconnetDevice];
}

@end
